package com.lee.taste.spider.sohu.spider;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.assertj.core.util.Lists;
import org.dom4j.Element;

import com.lee.taste.spider.HttpRequest;
import com.lee.taste.spider.sohu.db.BrandDao;
import com.lee.taste.spider.sohu.entity.Corporation;
import com.lee.taste.spider.sohu.entity.SaleCorp;
import com.lee.taste.spider.sohu.xml.XMLParase;
import com.lee.taste.spider.sohu.xml.XMLUtils;

public class CorpSpider {

	private static BrandDao brandDao = new BrandDao();
	public static List<Corporation> crawl(String url) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<Corporation> list = parseXml(XMLParase.parseXml(xml));  
		brandDao.batchUpdateCorp(list);
		return list;
	}
	public static void crawlSales(String url) throws Exception  {
		String xml = HttpRequest.sendGet(url, "");
		List<SaleCorp> list = parseSales(XMLParase.parseXml(xml));  
		brandDao.batchUpdateCorpSales(list);
	}
	private static List<Corporation>  parseXml(Element element){
		List<Corporation> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("corp");
		for(Element e : elesBrand){
			Corporation entity = new Corporation(XMLUtils.getAttributeValue(e,"id"),XMLUtils.getAttributeValue(e,"name"),XMLUtils.getAttributeValue(e,"brandId")
					,XMLUtils.getAttributeValue(e,"brandName"),XMLUtils.getAttributeValue(e,"letter"));
			list.add(entity);
		}
		return list;
	}
	private static List<SaleCorp>  parseSales(Element element){
		List<SaleCorp> list = Lists.newArrayList();
		if(element == null){
			return list;
		}
		List<Element> elesBrand = element.elements("sales");
		for(Element e : elesBrand){
			SaleCorp entity = new SaleCorp(XMLUtils.getAttributeValue( element,"id"),XMLUtils.getAttributeValue( element,"name")
					,XMLUtils.getAttributeValue(e,"date"),XMLUtils.getAttributeValue(e,"salesNum"));
			list.add(entity);
		}
		return list;
	}
}
